<template>
  <div class="statistics-report">
    <SearchForm
      v-model="searchParams"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 统计报表内容 -->
    <el-card class="report-card">
      <div class="report-header">
        <h2 class="report-title">按培养单位和高校统计表</h2>
        <p class="report-subtitle" :style="isPhone ? { display: 'block' } : {}">
          <div style="margin-right: 20px;">
            <span style="color: black;">累计培养人数（黑色）</span>/ <span style="color: #67c23a;">在企实践人数（绿色）</span>/ <span style="color: #f56c6c;">已毕业人数（红色）</span>
          </div>
          <div>
            总人数: <span class="highlight-number">{{ totalCount }}</span>
          </div>
        </p>
      </div>

      <!-- 多维表格 -->
      <div class="table-container" v-loading="loading">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :header-cell-style="headerCellStyle"
          :row-class-name="getRowClassName"
        >
          <!-- 培养单位列 -->
          <el-table-column prop="trainDeptName" label="培养单位" width="120" align="center" fixed>
            <template #default="{ row }">
              <span :class="{ 'total-row': row.isTotal }">
                {{ row.trainDeptName }}
              </span>
            </template>
          </el-table-column>

          <!-- 小计列 -->
          <el-table-column label="小计" width="120" align="center">
            <template #default="{ row }">
              <div v-html="formatSubtotalValue(row)"></div>
            </template>
          </el-table-column>

          <!-- 各高校列组 -->
          <el-table-column
            v-for="university in universityList"
            :key="university.value"
            :label="university.label"
            align="center"
          >
            <!-- 在校硕士 -->
            <el-table-column label="在校硕士" width="100" align="center">
              <template #default="{ row }">
                <div v-html="formatCellValue(row, university.value, 'fullTimeMastersCount')"></div>
              </template>
            </el-table-column>
            
            <!-- 在校博士 -->
            <el-table-column label="在校博士" width="100" align="center">
              <template #default="{ row }">
                <div v-html="formatCellValue(row, university.value, 'fullTimeDoctorCount')"></div>
              </template>
            </el-table-column>
            
            <!-- 在职博士 -->
            <el-table-column label="在职博士" width="100" align="center">
              <template #default="{ row }">
                <div v-html="formatCellValue(row, university.value, 'onTheJobDoctorCount')"></div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, getCurrentInstance } from "vue";
import SearchForm from "./searchForm.vue";
import { getTrainDeptUniversityStatistics } from "@/api/statistics";
import { ElMessage } from "element-plus";
import { isPhone } from "@/utils/index";

const { proxy } = getCurrentInstance();

// 搜索参数
const searchParams = ref({});

// 统计数据
const tableData = ref([]);
const loading = ref(false);

// 获取字典数据
const { university } = proxy.useDict("university");

// 计算总人数
const totalCount = computed(() => {
  if (tableData.value.length === 0) return 0;
  const totalRow = tableData.value.find(row => row.isTotal);
  return totalRow ? totalRow.total : 0;
});

// 获取所有高校列表
const universityList = computed(() => {
  if (!university.value || university.value.length === 0) return [];
  return university.value;
});

// 表头样式
const headerCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  return { 
    background: '#f5f7fa', 
    color: '#606266',
    textAlign: 'center',
    fontWeight: 'bold'
  };
};

// 获取行样式类名
const getRowClassName = ({ row, rowIndex }) => {
  if (row.isTotal) return 'total-row-class';
  return '';
};

// 格式化小计列数值（显示格式：总数/在企/毕业）
const formatSubtotalValue = (row) => {
  if (!row.subTotal) return '';
  
  const total = row.total || 0; // 总数
  const inEnterprise = row.subTotal.inEnterpriseCount || 0; // 入企人数
  const graduated = row.subTotal.graduatedCount || 0; // 毕业人数
  
  // 根据行类型设置字体粗细
  const fontWeight = row.isTotal ? '700' : '600';
  
  // 构建显示内容：总数/在企/毕业
  const parts = [];
  
  // 总数（黑色）
  parts.push(`<span style="color: #303133; font-weight: ${fontWeight};">${total}</span>`);
  
  // 在企人数（绿色）
  if (inEnterprise > 0) {
    parts.push(`<span style="color: #67c23a; font-weight: ${fontWeight};">${inEnterprise}</span>`);
  }
  
  // 毕业人数（红色）
  if (graduated > 0) {
    parts.push(`<span style="color: #f56c6c; font-weight: ${fontWeight};">${graduated}</span>`);
  }
  
  return parts.join('<span style="color: #909399;">/</span>');
};

// 格式化单元格数值（显示格式：总数/在企/毕业）
// 累计培养人数（黑色）/累计入企人数（绿色）/累计毕业人数（红色）
const formatCellValue = (row, universityKey, fieldType) => {
  const uniData = getUniversityData(row, universityKey);
  if (!uniData) return '';
  
  const typeData = uniData[fieldType];
  if (!typeData || !typeData.studentCount) return '';
  
  const studentCount = typeData.studentCount || 0; // 累计培养人数（总数）
  const inEnterprise = typeData.inEnterpriseCount || 0; // 在企实践人数
  const graduated = typeData.graduatedCount || 0; // 已毕业人数
  
  // 根据行类型设置字体粗细
  const fontWeight = row.isTotal ? '700' : '500';
  
  // 构建显示内容：总数/在企/毕业（所有行都按此格式显示）
  const parts = [];
  
  // 总数（黑色）
  parts.push(`<span style="color: #303133; font-weight: ${fontWeight};">${studentCount}</span>`);
  
  // 在企人数（绿色）
  if (inEnterprise > 0) {
    parts.push(`<span style="color: #67c23a; font-weight: ${fontWeight};">${inEnterprise}</span>`);
  }
  
  // 毕业人数（红色）
  if (graduated > 0) {
    parts.push(`<span style="color: #f56c6c; font-weight: ${fontWeight};">${graduated}</span>`);
  }
  
  return parts.join('<span style="color: #909399;">/</span>');
};

// 获取高校数据
const getUniversityData = (row, universityKey) => {
  if (!row.universityData || !row.universityData[universityKey]) {
    return null;
  }
  return row.universityData[universityKey];
};

// 处理表格数据
const processTableData = (data) => {
  if (!data || data.length === 0) return [];
  
  return data.map(item => {
    // 构建高校数据映射
    const universityData = {};
    if (item.universityDetailList && item.universityDetailList.length > 0) {
      item.universityDetailList.forEach(uni => {
        universityData[uni.trainUniversity] = {
          fullTimeMastersCount: uni.fullTimeMastersCount || null,
          fullTimeDoctorCount: uni.fullTimeDoctorCount || null,
          onTheJobDoctorCount: uni.onTheJobDoctorCount || null
        };
      });
    }
    
    return {
      trainDeptId: item.trainDeptId,
      trainDeptName: item.trainDeptName,
      total: item.total || 0,
      subTotal: item.subTotal,
      universityData,
      isTotal: item.trainDeptName === '合计',
      isSubtotal: item.trainDeptName === '小计'
    };
  }).filter(item => !item.isSubtotal); // 过滤掉小计行
};

// 加载统计数据
const loadStatistics = async () => {
  try {
    loading.value = true;
    
    const res = await getTrainDeptUniversityStatistics(searchParams.value);
    if (res.code === 200) {
      tableData.value = processTableData(res.data);
    } else {
      ElMessage.error(res.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("加载统计数据失败:", error);
    ElMessage.error("加载统计数据失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  console.log("搜索参数:", searchParams.value);
  loadStatistics();
};

// 重置处理
const handleReset = () => {
  console.log("重置搜索");
  loadStatistics();
};

// 组件挂载时加载数据
onMounted(() => {
  loadStatistics();
});
</script>

<style scoped>
.statistics-report {
  padding: 20px;
}

.report-card {
  margin-top: 20px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.report-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.report-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
  display: flex;
}

.highlight-number {
  color: #409eff;
  font-weight: bold;
  font-size: 1.1em;
}

.table-container {
  margin-top: 20px;
  overflow-x: auto;
}

.total-row {
  font-weight: bold;
  color: #303133;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  font-weight: 600;
  text-align: center;
  padding: 8px 0;
}

:deep(.el-table td) {
  text-align: center;
  padding: 10px 0;
}

:deep(.el-table--border) {
  border: 1px solid #dcdfe6;
}

:deep(.el-table--border td) {
  border-right: 1px solid #dcdfe6;
}

:deep(.el-table--border th) {
  border-right: 1px solid #dcdfe6;
}

/* 合计行样式 */
:deep(.total-row-class td) {
  background-color: #f5f7fa !important;
  font-weight: bold;
  color: #303133;
}

/* 固定列样式 */
:deep(.el-table__fixed) {
  box-shadow: 2px 0 6px rgba(0, 0, 0, 0.1);
}

/* 表格单元格内边距调整 */
:deep(.el-table .cell) {
  padding: 0 8px;
  line-height: 28px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .table-container {
    font-size: 13px;
  }
  
  :deep(.el-table .cell) {
    padding: 0 6px;
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .statistics-report {
    padding: 10px;
  }

  .report-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .report-title {
    font-size: 20px;
  }

  .report-subtitle {
    font-size: 14px;
  }

  .table-container {
    font-size: 12px;
  }

  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table .cell) {
    padding: 0 4px;
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .report-title {
    font-size: 18px;
  }

  .table-container {
    font-size: 11px;
  }

  :deep(.el-table) {
    font-size: 11px;
  }
  
  :deep(.el-table .cell) {
    padding: 0 3px;
    font-size: 11px;
  }
}
</style>